package com.eclipse.e20200131_模拟tomcat.moni_tomcat.tomcat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class Server {

	public static void main(String[] args) throws Exception {
		ServerSocket server = new ServerSocket(8080);

		System.out.println("Tomcat正在8080端口监听。。。。。");
		while (true) {
			// 阻塞，等待客户端连接
			Socket socket = server.accept();
			System.out.println("有客户连接。。。。。");
			new RequestHandler(socket).start();
		}

	}

}

class RequestHandler extends Thread {

	static Properties config = null;
	static {
		config = new Properties();
		try {
			config.load(new FileReader("src/moni_tomcat/tomcat/web.properties"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private Socket socket;

	// 保持url和servlet對象的映射关系
	private Map<String, HttpServlet> servlets = new HashMap<>();

	public RequestHandler(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		BufferedReader reader = null;
		BufferedWriter writer = null;
		try {
			System.out.println("----------------------------------");
			// 读取客户端的请求内容
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

			String requestLine = reader.readLine();
			System.out.println("http请求内容：" + requestLine);

			// 解析请求
			String[] temp = requestLine.split(" ");
			System.out.println("解析请求：。。。。。。。。。。。。。");
			for (String t : temp) {
				System.out.println(t);
			}
			//包到了Request对象中

			// 通过url部分获取Servlet的类全名
			String servletName = config.getProperty(temp[1]);
			System.out.println("servletName:" + servletName);
			HttpServlet servlet = null;
			if (!servlets.containsKey(temp[1])) {
				// 加载类文件，形成Class对象
				Class clz = Class.forName(servletName);

				// 使用class对象创建一个Servlet对象
				servlet = (HttpServlet) clz.newInstance();

				servlets.put(temp[1], servlet);
			}

			servlet.doGet(writer);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				reader.close();
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
}
